import { Card, Form, Input, Select, Button, Table, Tag, Badge, Popconfirm, message } from "antd";
import TitleHandlerDiv from "../../../../components/TableHandlerArea";
import React, { useState, useEffect } from "react";
import "./index.scss";
import { HeaderFormCom, PaginationCom } from "../../../../components/ArticleDetailCom/DrawerMultilayer/OssFileDrawer";
import api from "../../../../api";
import { useHistory } from "react-router-dom";
const { Option } = Select;
const { Column } = Table;
const Article = () => {
  const history = useHistory();
  const [classifyList, setClassifyList] = useState([]);
  const [articleList, setArticleList] = useState([]);
  const [selectedRows, setSelectedRows] = useState([]);
  const [total, setTotal] = useState(0);
  const onSelectChange = (selectedRowKeys, selectedRows) => {
    setSelectedRows([...selectedRows]);
  };
  const rowSelection = {
    selectedRows,
    onChange: onSelectChange,
  };
  const [form, setForm] = useState({
    pageIndex: 1,
    pageSize: 8,
    searchVal: "",
    state: null,
    classifyVal: null,
  });
  useEffect(() => {
    init();
  }, []);
  const init = () => {
    getClassifyList();
    getArticleList();
  };
  //获取分类列表
  const getClassifyList = async () => {
    const res = await api.getClassifyList();
    setClassifyList([...res.data]);
  };
  //获取文章列表
  const getArticleList = async () => {
    const res = await api.getArticle({ ...form });
    setArticleList([...res.data.res]);
    setTotal(res.data.total);
  };
  //select  change事件
  const handleChange = (value, type) => {
    console.log(value);
    form[type] = value;
    setForm({ ...form });
  };
  //form表单  change事件
  const changeFormValue = (value, type) => {
    form[type] = value;
    setForm({ ...form });
  };
  //重置表单
  const resetForm = () => {
    form.pageIndex = 1;
    form.pageSize = 8;
    form.searchVal = "";
    form.state = null;
    form.classifyVal = null;
    setForm({
      ...form,
    });
  };
  //删除(单个)
  const delArticleList = async (id) => {
    await api.delArticle({ id });
    await getArticleList();
    message.success("删除成功");
  };
  //改变首焦状态
  const changeFocusState = async (id) => {
    await api.changeArticleFocus({ id });
    await getArticleList();
    message.success("操作成功");
  };
  //批量操作函数   apiPath<string>  api下的函数名
  const batchHandlerList = async (apiPath) => {
    await api[apiPath]({ batchList: selectedRows });
    await getArticleList();
    message.success("操作成功");
  };
  //分页
  const changePagination = async (pageIndex, pageSize) => {
    form.pageIndex = pageIndex;
    form.pageSize = pageSize;
    await setForm({ ...form });
    getArticleList();
  };
  //跳转页面
  const goUrl = (path) => {
    history.push(path);
  };
  return (
    <div className="all-article">
      <Card>
        <HeaderFormCom handlerResetBtn={resetForm} handlerSearchBtn={getArticleList}>
          <Form layout="inline">
            <Form.Item label="标题">
              <Input placeholder="请输入文章标题" value={form.searchVal} onChange={(e) => changeFormValue(e.target.value, "searchVal")} />
            </Form.Item>
            <Form.Item label="状态">
              <Select value={form.state} style={{ width: 170 }} onChange={(e) => handleChange(e, "state")}>
                <Option value={1}>已发布</Option>
                <Option value={0}>草稿</Option>
              </Select>
            </Form.Item>
            <Form.Item label="分类">
              <Select style={{ width: 170 }} value={form.classifyVal} onChange={(e) => handleChange(e, "classifyVal")}>
                {classifyList?.length &&
                  classifyList.map((item) => {
                    return (
                      <Option value={item.text} key={item.id}>
                        {item.text}
                      </Option>
                    );
                  })}
              </Select>
            </Form.Item>
          </Form>
        </HeaderFormCom>
      </Card>
      <Card
        title={
          <TitleHandlerDiv showHandlerArea={selectedRows.length} handlerBtnClick={() => goUrl("/add/article")}>
            <div className="article_handler_btn">
              <Button onClick={() => batchHandlerList("batchPubArticle")}>发布</Button>
              <Button onClick={() => batchHandlerList("batchDftArticle")}>草稿</Button>
              <Button onClick={() => batchHandlerList("batchFocusArticle")}>首焦推荐</Button>
              <Button onClick={() => batchHandlerList("batchRemoveArticle")}>撤销首焦</Button>
              <Button danger onClick={() => batchHandlerList("batchDelArticle")}>
                删除
              </Button>
            </div>
          </TitleHandlerDiv>
        }
        className="table-card"
      >
        <Table
          rowSelection={{ type: "checkbox", ...rowSelection }}
          dataSource={articleList}
          rowKey="id"
          pagination={false}
          scroll={{ x: 1500 }}
          style={{ width: "100%", overflow: "none" }}
        >
          <Column title="标题" dataIndex="title" fixed="left" width={200} />
          <Column
            title="状态"
            dataIndex="state"
            render={(text) => {
              return (
                <>
                  <Badge dot color={Number(text) ? "#52C41A" : "#F5222D"}></Badge>
                  {Number(text) ? "已发布" : "草稿"}
                </>
              );
            }}
          />
          <Column
            title="分类"
            dataIndex="classify"
            align="center"
            render={(tag) => {
              return <Tag color="geekblue">{tag || ""}</Tag>;
            }}
          />
          <Column
            title="标签"
            dataIndex="tag"
            align="center"
            render={(tag) => {
              return <Tag color="green">{tag}</Tag>;
            }}
          />
          <Column
            title="阅读量"
            dataIndex="looks"
            align="center"
            render={(text) => {
              return <Badge showZero count={text || 0} style={{ backgroundColor: "#52c41a" }} />;
            }}
          />
          <Column
            title="喜欢数"
            dataIndex="likes"
            align="center"
            render={(text) => {
              return <Badge showZero count={text || 0} style={{ backgroundColor: "#ED4BA4" }} />;
            }}
          />
          <Column title="发布时间" dataIndex="release_time" align="center" />
          <Column
            width={330}
            title="操作"
            dataIndex="action"
            fixed="right"
            render={(text, record) => {
              return (
                <div>
                  <Button type="link" onClick={() => goUrl("/article/" + record.id)}>
                    编辑
                  </Button>
                  <Button type="link" onClick={() => changeFocusState(record.id)}>
                    {Boolean(Number(record.focus)) ? "撤销首焦" : "首焦推荐"}
                  </Button>
                  <Button type="link">查看访问</Button>
                  <Popconfirm title="确认删除这个文章？" okText="确认" cancelText="取消" onConfirm={() => delArticleList(record.id)}>
                    <Button type="link">删除</Button>
                  </Popconfirm>
                </div>
              );
            }}
          />
        </Table>
        <div className="pagination-box">
          <PaginationCom total={total} onChange={changePagination} pageSize={form.pageSize} pageIndex={form.pageIndex} />
        </div>
      </Card>
    </div>
  );
};

export default Article;
